package com.opengl.textprint.utils;

import android.content.Context;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.ImageSpan;

import org.xml.sax.XMLReader;

/**
 * Author: Wu Chang
 * 阅读模块的TagHandler
 * Date: 2023/4/28 16:07
 */
public class ClickTagHandler implements Html.TagHandler{

    /**
     * html代码段加载的开始与结束标记都是 HTML
     */
    private static final String START_END = "html";

    private static final String IMG = "img";

    private boolean isStartOrEnd = true;

    private OnTagHandlerListener listener;

    private Context context;

    public ClickTagHandler(Context context, OnTagHandlerListener listener) {
        this.context = context;
        this.listener = listener;
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        if (tag.equalsIgnoreCase(START_END)) {
            // 两次变化，结束的时候 值为true
            isStartOrEnd = !isStartOrEnd;
            if (isStartOrEnd) {
                if (listener != null) {
                    listener.onTagLoadFinish();
                }
            }
        } else if (tag.equalsIgnoreCase(IMG)) {
            // 图片标签
            int len = output.length();
            ImageSpan[] images = output.getSpans(len - 1, len, ImageSpan.class);
            String imgURL = images[0].getSource();
            // 使图片可点击并监听点击事件
            output.setSpan(new ReadClickableSpan(context, imgURL), len - 1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 连续的图片会导致加载的图片的点击区域出现重叠覆盖，导致展示图片与点击图片出现误差
            // 此处添加一个空的字符串，用于对图片区域进行分割，确保点击的图片与展示的大图一致
            output.append(" ");
        }
    }

    public interface OnTagHandlerListener {
        void onTagLoadFinish();
    }
}
